package com.hmtech.ayp.common.s3.controller;

import com.hmtech.ayp.common.resp.R;
import com.hmtech.ayp.common.s3.domain.S3UploadResult;
import com.hmtech.ayp.common.s3.service.IS3Service;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@RequestMapping("/api/s3")
@RestController
@Slf4j
@AllArgsConstructor
public class S3Controller {
    private final IS3Service s3Service;

    @PostMapping("/upload")
    public R<?> upload(@ModelAttribute MultipartFile file) {
        try {
            String tmpFilePath = System.getProperty("java.io.tmpdir") + "/" + file.getOriginalFilename();
            file.transferTo(new File(tmpFilePath));
            S3UploadResult s3UploadResult = s3Service.upload(tmpFilePath);
            s3UploadResult.setOriginalFilename(file.getOriginalFilename());
            return R.ok(s3UploadResult);
        } catch (Exception e) {
            log.error("将文件存入到临时文件失败！", e);
        }
        return R.internalError();
    }
}
